<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ attribute name="formName" required="true" rtexprvalue="true" description="no need to add a '#'"%>
<%@ attribute name="validateUrl" required="true" rtexprvalue="true" %>

<spring:url value="${validateUrl}" var="applicationForm" />

<script type="text/javascript">
	
	function collectFormData(fields){
		var map = {};
		for(var i=0;i<fields.length;i++){
			var field = $(fields[i]);
			map[field.attr('name')] = field.val();
		}
		return map;
	}
	
	$(function(){
		var $myForm = $("#${formName}");
		$myForm.bind("submit", function(event){
			
			var inputs = $myForm.find('input');
			var data = collectFormData(inputs);
			
			$myForm.find('.control-group').removeClass('error');
			$myForm.find('.help-inline').empty();
			
			$.post('${validateUrl}', data, function(response){
				if(response.failed ){
					
					for(var i=0;i < response.errorMessages.length;i++){
						var item = response.errorMessages[i];
						var $controlGroup = $('#' + item.fieldName);
						$controlGroup.addClass('error');
						$controlGroup.find('.help-inline').html(item.message);
					}
					
				}else{
					$myForm.unbind('submit');
					$myForm.submit();
				}
			}, "json");
			
			
			
			
			event.preventDefault();
			return false;
			
		});
	});
	</script>